package project;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
    private JFrame frame;
    private JTextField usernameTextField;
    private JPasswordField passwordField;
    private JButton loginButton;

    public Main() {
        initComponents();
        layoutComponents();
        addListeners();
        frame.setVisible(true);
    }

    private void initComponents() {
        frame = new JFrame("寝室管理登录器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        usernameTextField = new JTextField(15);
        passwordField = new JPasswordField(15);
        loginButton = new JButton("登录");
    }

    private void layoutComponents() {
        // 创建放置用户名和密码组件的面板，用FlowLayout实现水平居中
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        inputPanel.add(new JLabel("用户名："));
        inputPanel.add(usernameTextField);
        inputPanel.add(new JLabel("密码："));
        inputPanel.add(passwordField);

        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(inputPanel, BorderLayout.CENTER);

        // 创建放置按钮的面板，用FlowLayout实现按钮在底部水平居中
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(loginButton);
        frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    private void addListeners() {
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String inputUsername = usernameTextField.getText();
                char[] passwordChars = passwordField.getPassword();
                String inputPassword = new String(passwordChars);

                String correctUsername = "admin";
                String correctPassword = "123456";

                if (inputUsername.equals(correctUsername) && inputPassword.equals(correctPassword)) {
                    JOptionPane.showMessageDialog(frame, "登录成功，欢迎进入寝室管理系统！");
                } else {
                    JOptionPane.showMessageDialog(frame, "用户名或密码错误，请重新输入。");
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Main());
    }
}
